﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml.Linq;
using MM.DBUtility;

namespace MobileManager
{
    public partial class MruleManage : System.Web.UI.Page
    {
        private MM.Model.T_Users userModel;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Session["CurUser"] == null)
            {
                Response.Redirect("Login.aspx");
                return;
            }
            else
            {
                userModel = (MM.Model.T_Users)Session["CurUser"];
            }
            if (!IsPostBack)
            {
                BindDdlODEP(ref ddlODEP);
                ddlODEP.Items.Insert(0, new ListItem("全部", "-1"));

                BindDdlCustomer(ref ddlCustomer);
                ddlCustomer.Items.Insert(0, new ListItem("全部", "-1"));

                BindDdlChannel(ref ddlChannel);
                ddlChannel.Items.Insert(0, new ListItem("全部", "-1"));

                GVDataBind();
            }
        }

        #region DDL Bind
        private void BinDdlProvince(ref DropDownList ddl)
        {
            ddl.DataSource = BLSqlData.AllProvince;
            ddl.DataValueField = "ProvinceID";
            ddl.DataTextField = "ProvinceName";
            ddl.DataBind();
        }
        private void BindDdlODEP(ref DropDownList ddl)
        {
            ddl.DataSource = DbHelperSql.Query("SELECT ONO,ONO+'-'+ OName as Name FROM T_ODEP WITH(NOLOCK) ").Tables[0];
            ddl.DataValueField = "ONO";
            ddl.DataTextField = "Name";
            ddl.DataBind();
        }
        private void BindDdlCustomer(ref DropDownList ddl)
        {
            ddl.DataSource = DbHelperSql.Query("SELECT CNO,CNO+'-'+ CName as Name FROM T_Customers WITH(NOLOCK) ").Tables[0];
            ddl.DataValueField = "CNO";
            ddl.DataTextField = "Name";
            ddl.DataBind();
        }
        private void BindDdlChannel(ref DropDownList ddl)
        {
            ddl.DataSource = DbHelperSql.Query("SELECT ChannelNO,ChannelNO+'-'+ ChannelNumber+'-'+ChannelOrder as Name FROM T_Channel WITH(NOLOCK) order by ChannelNO ").Tables[0];
            ddl.DataValueField = "ChannelNO";
            ddl.DataTextField = "Name";
            ddl.DataBind();
        }
        #endregion

        #region GV Bind
        private void GVDataBind()
        {
            string strOrder = string.Empty;
            if ("PinYinCode".Equals(ddlOrder.SelectedValue))
                strOrder += string.Format(" ORDER BY b.PinYinCode,a.ONO {0}", ddlAD.SelectedValue);
            else strOrder += string.Format(" ORDER BY a.{0},a.ONO {1}", ddlOrder.SelectedValue, ddlAD.SelectedValue);

            string strSQL = string.Format(@"SELECT row_number() over({0}) rn,a.ID,b.ProvinceName,a.ONO,c.OName,a.CNO,d.CName,a.ChannelNO,e.ChannelNumber+'-'+e.ChannelOrder as ChannelName,
                            a.SendCount,a.NextTime,a.TimeInterval,a.Status FROM T_Rules a,T_Province b,T_ODEP c,T_Customers d,T_Channel e WITH(NOLOCK) 
                            WHERE a.ProvinceID=b.ProvinceID AND a.ONO=c.ONO AND a.CNO=d.CNO AND a.ChannelNO=e.ChannelNO ", strOrder);

            string strProvinceID = MM.DBUtility.BLSqlData.GetProvinceIDbyQuickName(txtProvince.TextValue);
            if (!string.IsNullOrEmpty(strProvinceID))
                strSQL += string.Format(" AND a.ProvinceID={0}", strProvinceID);
            if (!"-1".Equals(ddlODEP.SelectedValue))
                strSQL += string.Format(" AND a.ONO='{0}'", ddlODEP.SelectedValue);
            if (!"-1".Equals(ddlCustomer.SelectedValue))
                strSQL += string.Format(" AND a.CNO='{0}'", ddlCustomer.SelectedValue);

            if (!string.IsNullOrEmpty(userModel.CustomerNO))
                strSQL += string.Format(" AND a.CNO IN ({0})", BLSqlData.GetInSQL(userModel.CustomerNO));

            if (!"-1".Equals(ddlChannel.SelectedValue))
                strSQL += string.Format(" AND a.ChannelNO='{0}'", ddlChannel.SelectedValue);
            if (!"-1".Equals(ddlStatus.SelectedValue))
                strSQL += string.Format(" AND a.Status='{0}'", ddlStatus.SelectedValue);
            if (!string.IsNullOrEmpty(inputDate.Value))
                strSQL += string.Format(" AND a.NextTime='{0}'", inputDate.Value);

            AspNetPager1.RecordCount = DbHelperSql.GetCount("SELECT COUNT(1) FROM (" + strSQL + ") AS B");

            strSQL = string.Format("SELECT TOP {0} * FROM ({1}) AS F WHERE rn BETWEEN {2} AND {3}", AspNetPager1.PageSize, strSQL, (AspNetPager1.CurrentPageIndex - 1) * AspNetPager1.PageSize, AspNetPager1.CurrentPageIndex * AspNetPager1.PageSize - 1);

            DataSet ds = DbHelperSql.Query(strSQL);
            GVinfo.DataSource = ds;
            GVinfo.DataBind();
            ViewState["DataTemp"] = ds;
            lbCount.Text = "记录数：" + AspNetPager1.RecordCount;
        }
        protected void GVinfo_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            try
            {
                GVinfo.EditIndex = -1;
                GVinfo.DataSource = (DataSet)ViewState["DataTemp"];
                GVinfo.DataBind();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        protected void GVinfo_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow && (e.Row.RowState == DataControlRowState.Normal || e.Row.RowState == DataControlRowState.Alternate))
            {
                Label lbStatus = (Label)e.Row.FindControl("lbStatus");
                if (lbStatus.Text.Trim().Equals("1"))
                    lbStatus.Text = "开启";
                else if (lbStatus.Text.Trim().Equals("0"))
                    lbStatus.Text = "关闭";
            }
        }

        protected void GVinfo_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            try
            {
                string strID = ((HiddenField)GVinfo.Rows[e.RowIndex].FindControl("HF1")).Value;
                DbHelperSql.ExecuteSql(string.Format("DELETE FROM T_Rules WHERE ID={0}", strID));
                GVDataBind();
                //MM.DBUtility.BLSqlData.InsertLogs(userModel.UserID, string.Format("删除了规则信息：ID号={0}。", strID), "规则管理");
                MM.Common.Common.PageStartAlert(this.Page, "删除成功！");
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        protected void GVinfo_RowEditing(object sender, GridViewEditEventArgs e)
        {
            try
            {
                string strID = ((HiddenField)GVinfo.Rows[e.NewEditIndex].FindControl("HF1")).Value;
                Server.Transfer(string.Format("MruleManageEdit.aspx?ID={0}", strID));
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        protected void AspNetPager1_PageChanged(object sender, EventArgs e)
        {
            GVDataBind();
        }
        #endregion


        protected void btnQuery_Click(object sender, EventArgs e)
        {
            try
            {
                GVDataBind();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        private string UpdateIDs(string IDs)
        {
            if (IDs.Contains(","))
                IDs = IDs.Remove(IDs.LastIndexOf(","));

            return IDs;
        }

        protected void btnON_Click(object sender, EventArgs e)
        {
            try
            {
                string strIDs = UpdateIDs(hdfBoxValues.Value);
                if (!string.IsNullOrEmpty(strIDs))
                {
                    MM.DBUtility.DbHelperSql.ExecuteSql(string.Format("UPDATE T_Rules SET Status='1' WHERE ID IN ({0})", strIDs));
                    //MM.DBUtility.BLSqlData.InsertLogs(userModel.UserID, string.Format("更新了规则信息：状态=开启，ID={0}。", strIDs), "规则管理");
                    MM.Common.Common.PageStartAlert(this.Page, "状态更新成功！");
                    GVDataBind();
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        protected void btnOff_Click(object sender, EventArgs e)
        {
            try
            {
                string strIDs = UpdateIDs(hdfBoxValues.Value);
                if (!string.IsNullOrEmpty(strIDs))
                {
                    MM.DBUtility.DbHelperSql.ExecuteSql(string.Format("UPDATE T_Rules SET Status='0' WHERE ID IN ({0})", strIDs));
                    //MM.DBUtility.BLSqlData.InsertLogs(userModel.UserID, string.Format("更新了规则信息：状态=关闭，ID={0}。", strIDs), "规则管理");
                    MM.Common.Common.PageStartAlert(this.Page, "状态更新成功！");
                    GVDataBind();
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        protected void btnDeleteAll_Click(object sender, EventArgs e)
        {
            try
            {
                string strIDs = UpdateIDs(hdfBoxValues.Value);
                if (!string.IsNullOrEmpty(strIDs))
                {
                    MM.DBUtility.DbHelperSql.ExecuteSql(string.Format("DELETE FROM T_Rules WHERE ID IN ({0})", strIDs));
                    //MM.DBUtility.BLSqlData.InsertLogs(userModel.UserID, string.Format("删除了规则信息：ID={0}。", strIDs), "规则管理");
                    MM.Common.Common.PageStartAlert(this.Page, "删除成功！");
                    GVDataBind();
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
    }
}
